package de.unistuttgart.iaas.interaction.skype;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

//import de.unistuttgart.iaas.interaction.skype.util.CommonTools;
import de.unistuttgart.iaas.interaction.skype.util.TimeoutComputer;
import de.unistuttgart.iaas.interaction.skype.database.MySQLAccess;
import de.unistuttgart.iaas.interaction.skype.util.ConfigFileHandler;

public class ProcessMessage 
{

	public static void ProcessMessage(String configurationData)
	{
		try
		{
			ConfigFileHandler config = new ConfigFileHandler(configurationData);
			
			MySQLAccess dao = new MySQLAccess();
			Connection conn = dao.connDataBase(config);
			String getMessage = "select * from skydb."+config.getSkydb_table_sentTextMessage()+" where state in ('SENT','AWAIT_REPLY','REPLIED')";

			Statement statement = conn.createStatement();
			ResultSet rs = statement.executeQuery(getMessage);
			
			
			while(rs.next())
			{	
				ArrayList message = new ArrayList();
				
				for(int i=1; i<=9;i++)
				{
					message.add(rs.getString(i));
				}
				
				String skype_state =(String) message.get(8);
				
				if(skype_state.equalsIgnoreCase("SENT"))
				{
					ProcessSentMessage(config,message);
					
				}else if(skype_state.equalsIgnoreCase("AWAIT_REPLY"))
				{
					ProcessAwaitReplyMessage(config,message);
					
				}else if(skype_state.equalsIgnoreCase("REPLIED"))
				{
					ProcessRepliedMessage(config, message);
				}else
				{
					
				}
			}
			
			rs.close();
			statement.close();
			conn.close();
			
		}catch(Exception e)
		{
			System.out.println("Error in ProcessMail().");
		}
	}
	
	public static void ProcessSentMessage(ConfigFileHandler config, ArrayList list_SentMessage)
	{
		ArrayList list_AwaitReplyMessage   = new   ArrayList(); 
		
		String id = (String)list_SentMessage.get(0);
		String reply = (String)list_SentMessage.get(5);
		
		try
		{
			MySQLAccess dao = new MySQLAccess();
			Connection conn = dao.connDataBase(config);
			Statement update = conn.createStatement();
			
			if(reply.equalsIgnoreCase("no"))
			{
				update.executeUpdate("update skydb."+config.getSkydb_table_sentTextMessage()+" set state='FINISHED' where id='"+id+"'");
				System.out.println("id "+ id+"needs no response, set state=finished.");
				
			}else if(reply.equalsIgnoreCase("yes"))
			{	
				System.out.println("id "+ id +" needs response, set state=await_reply.");
				update.executeUpdate("update skydb."+config.getSkydb_table_sentTextMessage()+" set state='AWAIT_REPLY' where id='"+id+"'");
				list_SentMessage.set(8, "AWAIT_REPLY");
				list_AwaitReplyMessage= list_SentMessage;
				
				ProcessAwaitReplyMessage(config, list_AwaitReplyMessage); 
				
			}else
			{
				System.out.println("Error in ProcessSentMail( )");
			}
			
			update.close();
			conn.close();
			
		}catch(Exception e)
		{
			System.out.println("failed to process the request with id: "+id);
		}
	}
	
	public static void ProcessAwaitReplyMessage(ConfigFileHandler config, ArrayList list_AwaitReplyMessage) throws Exception
	{

		MySQLAccess dao = new MySQLAccess();
		Connection conn = dao.connDataBase(config);
		Statement awaitStatement = conn.createStatement();
		Statement update = conn.createStatement();
		
		ArrayList list_RepliedMessage = new ArrayList();
		
		boolean hasReply = false;
		
		String id = (String)list_AwaitReplyMessage.get(0);
		String timeout =(String)list_AwaitReplyMessage.get(7);
		
		
		ResultSet rsReply = awaitStatement.executeQuery("select * from skydb."+config.getSkydb_table_recievedTextMessage()+" where requestId='"+id+"' and state='NEW'");
		
		while(rsReply.next())
		{
			hasReply = true;
			String receiveTime = rsReply.getString("recievedDate");
			
			if(TimeoutComputer.isTimeout(timeout, receiveTime))
			{
				//timeout
				update.executeUpdate("update skydb."+config.getSkydb_table_sentTextMessage()+" set state='TIMEOUT' where id='"+id+"'");
				System.out.println("id "+id+" is timeout, set state= timeout, send timeout message back.");
				
			}else
			{
				update.executeUpdate("update skydb."+config.getSkydb_table_sentTextMessage()+" set state='REPLIED' where id='"+id+"'");
				
				list_AwaitReplyMessage.set(8, "Replied");
				list_RepliedMessage = list_AwaitReplyMessage;
				
				ProcessRepliedMessage(config,list_RepliedMessage);	
				
			}
		}
		
		if(!hasReply)
		{
			Calendar cal = Calendar.getInstance();
			DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  			
			String now = df.format(cal.getTime());
			if(TimeoutComputer.isTimeout(timeout, now))
			{
				//timeout
				update.executeUpdate("update skydb."+config.getSkydb_table_sentTextMessage()+" set state='TIMEOUT' where id='"+id+"'");
				System.out.println("id "+id+" is timeout, set state= timeout, send timeout message back.");													
			}
		}
		
		rsReply.close();
		awaitStatement.close();
		update.close();
		conn.close();
		
	}
	
	
	public static void ProcessRepliedMessage(ConfigFileHandler config, ArrayList list_RepliedMessage) throws Exception
	{
		MySQLAccess dao = new MySQLAccess();
		Connection conn = dao.connDataBase(config);
		Statement repliedStatement = conn.createStatement();
		Statement update = conn.createStatement();
		
		ArrayList list_response = new ArrayList();
		
		String id = (String)list_RepliedMessage.get(0);
		String responseTemplate = (String)list_RepliedMessage.get(6);
		System.out.println(responseTemplate);
		String timeout = (String)list_RepliedMessage.get(7);
		ResultSet rsReply = repliedStatement.executeQuery("select * from skydb."+config.getSkydb_table_recievedTextMessage()+" where requestId='"+id+"' and state='NEW'");

		boolean isValidResponse = false;
		
		while(rsReply.next())
		{
			for(int i=1; i<=10;i++)
			{
				list_response.add(rsReply.getString(i));
			}
			
			String requestId = rsReply.getString("id");
			//
//			String res = CommonTools.getResponse(list_response);
//			
//			if(!res.equals(""))
//			{
//				isValidResponse = CommonTools.isValidResponse(config, res, mail_responseTemplate);
//			}else
//			{
//				isValidResponse = false;
//			}
//			
//										
//			if(isValidResponse)
//			{
//				//valid response, request is finished, send response back.
//				update.executeUpdate("update maildb."+config.getTable_sentmails()+" set mail_state='FINISHED' where mail_id='"+mail_id+"'");
//				update.executeUpdate("update maildb."+config.getTable_mailbox()+" set mail_state='FINISHED' where mail_id='"+repliedId+"'");
//				Statement attStatement = conn.createStatement();
//				ResultSet rs = attStatement.executeQuery("select filename from maildb."+config.getTable_mailattachments()+" where mail_id='"+mail_id+"'");
//				String attachments ="";
//				while(rs.next())
//				{
//					attachments = rs.getString("filename")+"\n";
//				}
//				logger.info("recieve a response of mail_ID: "+repliedId+"send this response("+res+") back.");
//				System.out.println("recieve a response of mail_ID: "+repliedId+"send this response("+res+") back.");
//				if(!attachments.equals(""))
//				{
//					logger.info("With attachment:\n"+ attachments);
//					System.out.println("With attachment:\n"+ attachments);
//				}
//				
//			}else
//			{
//				//invalid response
//				Calendar cal = Calendar.getInstance();
//				DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  			
//				String now = df.format(cal.getTime());
//				if(TimeoutComputer.isTimeout(mail_timeout, now))
//				{
//					//timeout
//					update.executeUpdate("update maildb."+config.getTable_sentmails()+" set mail_state='TIMEOUT' where mail_id='"+mail_id+"'");
//					update.executeUpdate("update maildb."+config.getTable_mailbox()+" set mail_state='FAILED' where mail_id='"+repliedId+"'");
//
//					logger.info("mail_id "+mail_id+" is timeout, set mail_state= timeout, send timeout message back.");
//					System.out.println("mail_id "+mail_id+" is timeout, set mail_state= timeout, send timeout message back.");
//														
//				}else
//				{
//					String mail_body="";
//					Statement rsBodyStatement = conn.createStatement();
//					ResultSet rsBody = rsBodyStatement.executeQuery("select mail_message from maildb."+config.getTable_sentmails()+" where mail_id='"+mail_id+"'");
//					rsBody.next();
//					mail_body = "Invalid response(s)!\n"+rsBody.getString("mail_message");
//					//no timeout, resend the request, set new mail_sentDate
//					update.executeUpdate("update maildb."+config.getTable_sentmails()+" set mail_state='NEW', mail_sentDate='"+now+"', mail_message='"+mail_body+"' where mail_id='"+mail_id+"'");
//					update.executeUpdate("update maildb."+config.getTable_mailbox()+" set mail_state='FAILED' where mail_id='"+repliedId+"'");
//					
//					logger.info("Request(mail-id: "+mail_id+") will be resent.");
//					System.out.println("Request(mail-id: "+mail_id+") will be resent.");
//				}
//			}
		}
		rsReply.close();
		repliedStatement.close();
		update.close();
	}

		
	

}
